package com.emuporium.gymrat.server.routine;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emuporium.gymrat.server.data.ExerciseDB;
import com.emuporium.gymrat.server.data.Routine;
import com.emuporium.gymrat.server.data.RoutineDB;
import com.emuporium.gymrat.server.data.User;
import com.emuporium.gymrat.server.data.UserDB;
import com.emuporium.gymrat.server.data.Variation;
import com.google.gson.Gson;

@SuppressWarnings("serial")
public class RoutineAddEntryServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int routineId = new Integer(request.getParameter("routine")).intValue();
		Routine routine = RoutineDB.selectRoutine(routineId);
		request.setAttribute("routine", routine);
//		HttpSession session = request.getSession();
//		User user = (User) session.getAttribute("user");
		User user = UserDB.selectUser(request.getRemoteUser());

		Map<Integer, String> muscleGroups = new LinkedHashMap<Integer, String>();
		Map<String, Map<String, Integer>> exercises = new HashMap<String, Map<String, Integer>>();
		ArrayList<Variation> variations = new ArrayList<Variation>();

		muscleGroups = ExerciseDB.selectMuscleGroups();
		variations = ExerciseDB.selectAllVariations(user.getId());

		for (String muscleGroup : muscleGroups.values()) {
			exercises.put(muscleGroup, ExerciseDB.selectExercises(muscleGroup));
		}

		// Return Maps as JSON objects for javascript to parse
		request.setAttribute("exercises", new Gson().toJson(exercises));
		request.setAttribute("musclegroups", new Gson().toJson(muscleGroups));
		request.setAttribute("groupsarray", muscleGroups);
		request.setAttribute("variations", variations);

		String url = "/routine/addEntry.jsp";
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
